<template>
  <div>
    <div class="main">
      <div class="left" />
      <div class="right">
        <div class="loginArea">
          <div class="title">智慧园区-登录</div>
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
            <el-form-item prop="username">
              账号<el-input v-model="loginForm.username" style="width:80%" maxlength="12" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item prop="password">
              密码<el-input
                v-model="loginForm.password"
                style="width:80%"
                maxlength="10"
                type="password"
                placeholder="请输入密码"
              />
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button class="loginbtn" type="primary" @click="login">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { FORMDATA_KEY } from '@/constants/KEY'
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        remember: false
      },
      loginRules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  created() {
    const userPassObj = JSON.parse(localStorage.getItem(FORMDATA_KEY))
    if (userPassObj) {
      this.loginForm = userPassObj
    }
  },
  methods: {
    async login() {
      this.$refs.loginForm.validate(async(valid) => {
        if (valid) {
          await this.$store.dispatch('user/loginAction', this.loginForm)
          this.$message.success('登陆成功')
          if (this.loginForm.remember) {
            localStorage.setItem(FORMDATA_KEY, JSON.stringify(this.loginForm))
          } else {
            localStorage.removeItem(FORMDATA_KEY)
          }
          this.$router.push('/')
        } else {
          this.$message.error('请输入正确的用户名和密码')
        }
      })
    }
  }
}

</script>

<style scoped lang="scss">
.main {
  display: flex;
  height: 100vh;
}

.left {
  background-color: #fff;
  width: 1200px;
  height: 100%;
}

.right {
  flex: 1;
  height: 100%;
  background-color: skyblue;
  display: flex;
  justify-content: center;
  align-items: center;

  .loginArea {
    background-color: #fff;
    height: 400px;
    width: 400px;

    .title {
      text-align: center;
      font-size: 30px;
    }

    .el-form-item {
      margin-top: 35px;
      text-align: center
    }

    .el-form-item:nth-child(3) {
      text-align: left;
      margin-left: 30px;
      margin-top: 0px
    }

    ::v-deep .el-form-item__error {
      margin-left: 55px;
    }
  }
}
</style>
